import { _deepClone } from '@/utils'
import { Message } from 'element-ui'
import store from '@/store'
export function generateSqlString(relations, isValueEmpty) {
  const data = [];
  const relation = relations[0];
  const options = relations[1];
  if (typeof relation === "string") {
    options.forEach(opt => {
      if (Object.prototype.toString.call(opt) === "[object Object]" && opt.fieldName && isValueEmpty) {
        data.push(`${opt.fieldName} ${opt.operator} "${opt.value}"`);
      } else if (Object.prototype.toString.call(opt) === "[object Object]" && opt.fieldName && opt.value) {
        data.push(`${opt.fieldName} ${opt.operator} "${opt.value}"`);
      } else if (Object.prototype.toString.call(opt) === "[object Array]") {
        data.push(`(${generateSqlString(opt, isValueEmpty)})`);
      }
    });
  } else {
    if (relation.fieldName) {
      data.push(`${relation.fieldName} ${relation.operator} "${relation.value}"`);
    }
  }
  return data.join(` ${relation} `);
}

export function generateSqlObj(relations) {
  const data = [];
  const relation = relations[0];
  const options = relations[1];
  if (typeof relation === "string") {
    try {
      options.forEach(opt => {
        if (Object.prototype.toString.call(opt) === "[object Object]" && opt.fieldName) {
          if (!opt.value) {
            throw Error()
          } else {
            data.push({
              data: opt,
              operate: relation
            });
          }
        } else if (Object.prototype.toString.call(opt) === "[object Array]") {
          data.push(generateSqlObj(opt));
        }
      });
      return {
        operate: relation,
        chd: data
      };
    } catch (e) {
      return false;
    }
  } else {
    data.push(relation);
    return {
      operate: relation,
      chd: data
    };
  }

}

export function generateTuple(relations) {
  var tuple = [];
  if (relations.chd) {
    tuple[0] = relations.operate;
    const chd = relations.chd;
    tuple[1] = chd.map(item => {
      if (item.chd) {
        return generateTuple(item);
      } else {
        return item.data
      }
    });
  }
  return tuple;
}

export function replaceOperator(val) {
  return val.replaceAll("NEQ", "!=").replaceAll("EQ", "=").replaceAll("GT", ">")
    .replaceAll("LT", "<").replaceAll("GTE", ">=").replaceAll("LTE", "<=")
    .replaceAll("NOTIN", "notin").replaceAll("IN", "in").replaceAll("NOTLIKE", "notlike").replaceAll("LIKE", "like").replaceAll("IS", "is").replaceAll("FULL", 'full')
    .replaceAll("NOTREG", "notreg").replaceAll("REG", "reg");
}

export function setOperatorList(item) {
  if (item.columnType === "keyword") {
    item.operatorList = [
      { paramName: "=", paramValue: "EQ" },
      {
        paramName: "!=",
        paramValue: "NEQ",
      },
      {
        paramName: "is",
        paramValue: "IS",
      },
      {
        paramName: "like",
        paramValue: "LIKE",
      },
      {
        paramName: "notlike",
        paramValue: "NOTLIKE",
      },
    ];
  } else if (
    item.columnType === "Long" ||
    item.columnType === "Integer" ||
    item.columnType === "Double"
  ) {
    item.operatorList = [
      { paramName: "=", paramValue: "EQ" },
      {
        paramName: "!=",
        paramValue: "NEQ",
      },
      { paramName: ">", paramValue: "GT" },
      { paramName: "<", paramValue: "LT" },
      {
        paramName: ">=",
        paramValue: "GTE",
      },
      {
        paramName: "<=",
        paramValue: "LTE",
      }
    ];
  } else if (
    item.columnType === "Date" ||
    item.columnType === "geopoint"
  ) {
    item.operatorList = [
      { paramName: ">", paramValue: "GT" },
      { paramName: "<", paramValue: "LT" },
      {
        paramName: ">=",
        paramValue: "GTE",
      },
      {
        paramName: "<=",
        paramValue: "LTE",
      }
    ];
  } else if (item.columnType === "text") {
    item.operatorList = [
      {
        paramName: "full",
        paramValue: "FULL",
      },
      {
        paramName: "like",
        paramValue: "LIKE",
      },
      {
        paramName: "notlike",
        paramValue: "NOTLIKE",
      },
    ];
  } else if (item.columnType === "String") {
    item.operatorList = [
      { paramName: "=", paramValue: "EQ" },
      {
        paramName: "!=",
        paramValue: "NEQ",
      },
      { paramName: ">", paramValue: "GT" },
      { paramName: "<", paramValue: "LT" },
      {
        paramName: "like",
        paramValue: "LIKE",
      },
      {
        paramName: "notin",
        paramValue: "NOTIN",
      },
      {
        paramName: "reg",
        paramValue: "REG",
      },
      {
        paramName: "notreg",
        paramValue: "NOTREG",
      },
      {
        paramName: "is",
        paramValue: "IS",
      }, {
        paramName: "in",
        paramValue: "IN",
      }
    ];
  } else {
    item.operatorList = [
      { paramName: "=", paramValue: "EQ" }
    ]
  }
}

export function getSingleArray(arr) {
  if (arr && arr.length > 0) {
    return [].concat(...arr.map(item => {
      return item.children ? [].concat(item, ...getSingleArray(item.children)) : [].concat(item)
    }))
  }
  return []
}

export function flattern(data, parent) {
  var result = [];
  data.slice().forEach(item => {
    if (parent) {
      item.parent = parent;
    }
    const children = item.children;
    // delete item.children;
    result.push(item);
    if (children) {
      const parentIds = item.parent || [];
      result.push(...flattern(children, [...parentIds, item.id]))
    }
  })
  return result;
}

export function findIdParents(data, id) {
  const list = flattern(data);
  const item = list.find(item => item.id === id);
  if (!item) return "";
  return [...(item.parent || []), item.id].join(",");
}

export function getFullDept(val) {
  return val ? val.replaceAll(",", "/") : ''
}

export function commitData(commit) {
  commit("SET_THEME");
  commit("SET_SIDE_THEME");
  commit("SET_TOP_NAV");
  commit("SET_FONT_COLOR");
}

export function getRuleCondition(ruleDetails) {
  if (ruleDetails) {
    let ruleDetailsObj = JSON.parse(ruleDetails);
    if (ruleDetailsObj.condition) {
      return replaceOperator(
        generateSqlString(generateTuple(ruleDetailsObj.condition))
      );
    }

    let condition1, condition2;
    if (
      ruleDetailsObj.alertConditions &&
      (ruleDetailsObj.alertConditions[0].condition ||
        ruleDetailsObj.alertConditions[1].condition)
    ) {
      condition1 = generateSqlString(
        generateTuple(ruleDetailsObj.alertConditions[0].condition)
      );
      condition2 = generateSqlString(
        generateTuple(ruleDetailsObj.alertConditions[1].condition)
      );
      return replaceOperator(condition1 + ", " + condition2);
    }

    return "";
  }
}

export function getHasPermission(value) {
  const all_permission = "*:*:*";
  let flag = false;

  const permissions = store.getters && store.getters.permissions

  if (value && value instanceof Array && value.length > 0) {
    const hasPermissions = permissions.some((permission) => {
      return all_permission === permission || value.includes(permission);
    });

    flag = hasPermissions ? true : false;
  } else {
    flag = false;
  }

  return flag;
}

/**
 * 分页带模糊搜索
 * @param array
 * @param pageNum 页码
 * @param pageSize  每页显示条目个数
 * @param filterForm 筛选值和筛选字段名 {value, key}
 * @param initForm 如果有初始化默认值，会将默认值对应的数组对象放第一个（参数{value, key}）
 * @returns {*[]|*}
 */
export function initPagination(array, pageNum, pageSize, filterForm, initForm) {
  if (((pageSize !== undefined || true) && pageSize < 1) || !array.length) {
    return []
  }
  let result = array
  //模糊搜索 不区分大小写
  if (filterForm && filterForm.value && filterForm.key) {
    result = array.filter(item => item[filterForm.key].toLowerCase().indexOf(filterForm.value.toLowerCase()) !== -1)
    if (result.length === 0) return []
  }
  //如果初始化有值，找到对应的数据，在数组第一条展示
  if (initForm && initForm.value && initForm.key) {
    let index = array.findIndex(item => item[initForm.key].indexOf(initForm.value) !== -1)
    if (index > -1) {
      array.splice(0, 0, array.splice(index, 1)[0]);
    }
  }
  let size = pageSize ?? 10,//默认10条展示
    totalPage = Math.ceil(array.length / pageSize),//总页码
    currentIndex = 1,//标记当前页码
    viewData = [],//总数据
    item = [] //每页数据
  for (let i = 0; i < result.length; i++) {
    if (i === currentIndex * size) {
      currentIndex++
      item = []
    }
    item.push(result[i])
    viewData[currentIndex - 1] = item
  }
  // console.log(viewData)
  return pageNum - 1 > totalPage || pageNum < 1 ? [] : viewData[pageNum - 1]
}

//判断是否是JSON格式
export function isJSON(str) {
  if (typeof str === "string") {
    try {
      let obj = JSON.parse(str);
      if (typeof obj === "object" && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false
    }
  }
}

//数字格式化， 每三位逗号分隔
export function formatNumber(num) {
  return Number(num).toLocaleString()
}
export function createNonceStr() {
  let chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
    'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
    'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
    'x', 'y', 'z'
  ];
  let strs = "";
  for (let i = 0; i < 16; i++) {
    let id = parseInt(Math.random() * 61);
    strs += chars[id];
  }
  return strs;
}

export function getPercent(num, total) {
  num = parseFloat(num);
  total = parseFloat(total);
  if (isNaN(num) || isNaN(total)) {
    return "0%";
  }
  return total <= 0
    ? "0%"
    : Math.round((num / total) * 10000) / 100.0 + "%";
}
